package com.tf8.treasure.support.converter;

import com.google.common.base.Converter;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

@Component
public class GuavaConverterHolder implements InitializingBean, ApplicationContextAware {

    private final static ConcurrentMap<Class, Converter> converters = new ConcurrentHashMap<>();

    private ApplicationContext applicationContext;

    public static <A, B> Converter<A, B> getConverter(Class formType) {
        return converters.get(formType);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        final Map<String, Converter> converterMap = this.applicationContext.getBeansOfType(Converter.class);
        for (Converter converter : converterMap.values()) {
            if (converter instanceof Supportable) {
                for (Class support : ((Supportable<Class>)converter).supports()) {
                    converters.putIfAbsent(support, converter);
                }
            }
        }
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}